package com.example.chapter06;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.chapter06.util.FileUtil;
import com.example.chapter06.util.ToastUtil;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

public class ImageWriteActivity extends AppCompatActivity implements View.OnClickListener {

    private String path;
    private ImageView iv_content;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_image_write);

        findViewById(R.id.btn_save).setOnClickListener(this);
        findViewById(R.id.btn_read).setOnClickListener(this);
        iv_content = findViewById(R.id.iv_content);
    }

    @Override
    public void onClick(View v) {
        if(v.getId() == R.id.btn_save){
            String fileName = System.currentTimeMillis()+".jpeg";
            //获取当前APP的私有下载目录  File.separatorChar------/
            path = Objects.requireNonNull(getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)).toString()+
                    File.separatorChar +fileName;
            Log.d("liu",path);
            // 从指定资源文件中获取位图对象、
            Bitmap b1 = BitmapFactory.decodeResource(getResources(), R.drawable.ting2);
            //把位图对象保存为图片文件
            try {
                FileUtil.saveImage(path,b1);
                ToastUtil.show(this,"保存成功");
            } catch (IOException e) {
                throw new RuntimeException(e);
            }


        }
        if(v.getId() == R.id.btn_read){
            //读取的方法一：
            /*
            *try {
                Bitmap b2 =  FileUtil.openImage(path);
                iv_content.setImageBitmap(b2);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }*/

            //读取方法二
            /*
            *Bitmap b2 = BitmapFactory.decodeFile(path);
            iv_content.setImageBitmap(b2);*/

            //读取方法三：直接调用setImageURI方法，设置图像视图的路径对象
            iv_content.setImageURI(Uri.parse(path));
        }
    }
}